package com.ac.input.taglib;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;

import com.ac.input.dm.HndInpDef;
import com.ac.input.dm.HndInpDefItm;
import com.ac.input.web.form.DataSearchForm;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright AgileCentury 2004</p>
 * <p>Company: AgileCentury</p>
 * @author <a href="mailto:lianzs@tom.com">Lianzs</a>
 * @version 1.0
 */

public class QryScriptTag extends BodyTagSupport {
	private static final long serialVersionUID = 1L;
	private String formName;	
	
    public QryScriptTag() {
		super();
	}

	public void release() {
		super.release();
		formName = null;
	}

    public void setFormName(String formName) {
        this.formName = formName;
    }

    public String getFormName() {
        return formName;
    }

    public int doStartTag() throws JspException {
		return EVAL_BODY_INCLUDE;
	}

	public int doEndTag() throws JspException {
		StringBuffer results = new StringBuffer("");
		StringBuffer sbTemp = new StringBuffer("");
		HttpSession session = pageContext.getSession();
		DataSearchForm myForm = (DataSearchForm) session.getAttribute(formName);

		HndInpDef dm = myForm.getRhid();
		List dmList = dm.getViewClass().getChildren();
		results.append(getStartElement());
		sbTemp.append("function procSelectField(fieldName,opts){\n");
		sbTemp.append("  if (fieldName =='999999'){\n");
		
		for (int i = 0; i < dmList.size(); i++) {
			HndInpDefItm dmItem = (HndInpDefItm) dmList.get(i);
			if ("4".equals(dmItem.getVisTyp())) {
				sbTemp.append("  }else if (fieldName =='" + dmItem.getColCode() + ".4'){\n");
				sbTemp.append("    proc" + dmItem.getColCode() + "(opts);\n");
				
				results.append("function  proc" + dmItem.getColCode() + "(opts){\n");
				List dtList = dmItem.getListData();
				for (int j = 0; j < dtList.size(); j++) {
					Object[] cList = ((Map) dtList.get(j)).values().toArray();
					results.append("  opts.options[opts.length] = new Option(\"")
					       .append(cList[1])
					       .append("\", \"")
					       .append(cList[0])
					       .append("\");\n");
				}
				results.append("}\n");
			}
		}
		sbTemp.append("  }\n");
		sbTemp.append("}\n");
		results.append(sbTemp);
		results.append(getEndElement());
		
		try {
			pageContext.getOut().print(results);
		} catch (IOException ex) {
			ex.printStackTrace();
			throw new JspException("Error - tag.getProperty : IOException ");
		}
		return EVAL_PAGE;
	}

	protected String getStartElement() {
		return "<script type=\"text/javascript\"> \n";
	}

	protected String getEndElement() {
		return "\n</script>\n";
	}
}
